<template>
  <div :id="mapId" style="width: 100%; height: 520px;"></div>
</template>

<script>
import _ from 'lodash';
function isScriptAlreadyLoaded(srcCheck) {
  var scripts = document.getElementsByTagName('script');
  for (var i = 0; i < scripts.length; i++) {
      if (scripts[i].src.includes(srcCheck)) {
          return true; // 如果找到匹配的src，返回true
      }
  }
  return false; // 如果没有找到匹配的src，返回false
}

export default {
  name: "ViewFenceMap",
  data() {
    return {
      visible: false,
      title: "圆形",
      map: null,
      value: '',
      center: '',
      shapeType: '',
      mapId: '',
    };
  },
  methods: {
    show(shapeType, center, value, mapId='view_fence_map') {
      this.value = value,
      this.center = center,
      this.shapeType = shapeType,
      this.mapId = mapId;
      this.showMap();
    },
    async showMap(){
      await this.loadScript();
      if(!this.map){
        let point;
        if(_.isEmpty(this.center)){
          point = await this.getPoint();
        }else{
          point = this.center;
        }
        this.$nextTick(() => {
          this.initMap(point);
        })
      }else{
        if (this.fenceObj) {
          this.fenceObj.setMap(null); // 清除之前的形状
        }
        // 重新设置地图中心点
        if(this.center){
          let point = this.center;
          const center = new google.maps.LatLng(point.latitude, point.longitude);
          this.map.setCenter(center);
        }
        if(this.shapeType == "circle"){
          this.drawCircle();
        }
        if(this.shapeType == "polygon"){
          this.drawPolygon();
        }
      }
    },
    async loadScript() {
      const KEY = window._CONFIG['gMapKey'];
      const scriptSrc = `https://maps.googleapis.com/maps/api/js?libraries=geometry&key=${KEY}`;
      return new Promise((resolve, reject) => {
        if (isScriptAlreadyLoaded(scriptSrc)) {
          console.log('The script has already been loaded.');
          resolve(); // 如果脚本已经加载，则直接解决 Promise
        } else {
          const script = document.createElement("script");
          script.type = "text/javascript";
          script.src = scriptSrc;
          script.onload = () => {
            console.log('Script loaded successfully.', scriptSrc);
            resolve(); // 脚本加载完成后解决 Promise
          };
          script.onerror = (error) => {
            console.error('Error loading script:', error);
            reject(error); // 脚本加载出错时拒绝 Promise
          };
          document.body.appendChild(script);
        }
      });
    },
    initMap(point) { 
      console.log('初始化地图-----------------:');
      const center = new google.maps.LatLng(point.latitude, point.longitude);
      this.map = new google.maps.Map(document.getElementById(this.mapId), {
          zoom: 12, // 设置地图缩放级别
          center: center, // 设置地图中心点坐标
      });
      if(this.shapeType == "circle"){
        this.drawCircle();
      }
      if(this.shapeType == "polygon"){
        this.drawPolygon();
      }
    },
    drawCircle() {
      this.fenceObj = new google.maps.Circle({
        strokeColor: '#3777FF',
        strokeOpacity: 1,
        strokeWeight: 2,
        fillColor: '#3777FF',
        fillOpacity: 0.6,
        map: this.map
      });
      if(!_.isEmpty(this.value)){
        const obj = this.value;
        this.fenceObj.setCenter(new google.maps.LatLng(obj.latitude, obj.longitude));
        this.fenceObj.setRadius(obj.radius);
      }
    },
    drawPolygon(){
      this.fenceObj = new google.maps.Polygon({
        strokeColor: '#3777FF',
        strokeOpacity: 1,
        strokeWeight: 2,
        fillColor: '#3777FF',
        fillOpacity: 0.6,
        map: this.map
      });

      if(!_.isEmpty(this.value)){
        const objarr = this.value;
        const path = [];
        objarr.forEach((item)=>{
          const lat = item.latitude;
          const lng = item.longitude;
          path.push(new google.maps.LatLng(lat,lng));
        })
        this.fenceObj.setPath(path);
      }
    },
    //定义一个方法，通过腾讯地图给我一个本地的经纬度单做地图中心点坐标
    getPoint() {
      return new Promise((resolve, reject) => {
        if (!navigator.geolocation) {
          reject("Geolocation is not supported by this browser.");
        }
        navigator.geolocation.getCurrentPosition((position)=> {
          const point = {
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
          };
          console.log("经纬度", point);
          resolve(point);
        }, (error)=> {
          reject(error);
        });
      });
    },
  },
}
</script>

<style scoped>
</style>